#include "mainwindow.h"
#include <QMessageBox>
#include <QDesktopWidget>
#include <QUrl>
#include <QDir>
#include <QFile>
#include <QDebug>
#include "ui_mainwindow.h"
#include "customdialog.h"
#include "aboutwidget.h"

MainWindow::MainWindow(QWidget *parent)
	: QMainWindow(parent), ui(new Ui::MainWindowClass)
{
	ui->setupUi(this);

	//this->setSizePolicy(QSizePolicy::Fixed,QSizePolicy::Fixed);
	QDesktopWidget dsk;
	QRect rc=dsk.availableGeometry();
	int x=(rc.width()-width())/2;
	int y=(rc.height()-height())/2;
	setGeometry(x,y,width(),height());

	m_pProcess = NULL;
	ReadXml();
	createActions();
	m_pTray=new QSystemTrayIcon(this);
	QObject::connect(m_pTray,SIGNAL(activated(QSystemTrayIcon::ActivationReason)),this,SLOT(on_tray_activated(QSystemTrayIcon::ActivationReason)));
	trayIconMenu = new QMenu(this);

	trayIconMenu->addAction(playAction);
	trayIconMenu->addAction(pauseAction);
	trayIconMenu->addAction(stopAction);
	trayIconMenu->addSeparator();
	trayIconMenu->addAction(minimizeAction);
	trayIconMenu->addAction(maximizeAction);
	trayIconMenu->addAction(restoreAction);
	trayIconMenu->addSeparator();
	trayIconMenu->addAction(quitAction);
	m_pTray->setIcon(this->windowIcon());
	m_pTray->setToolTip("RadioGet");
	m_pTray->setContextMenu(trayIconMenu);
	m_pTray->show();

#ifndef Q_OS_WIN32
	QFile file("/usr/bin/mplayer");
	if(!file.exists()){
		QMessageBox::critical(this,"RadioGet","没有安装mplayer，无法正常工作！");
	}
#else
	QString strMplayer=QCoreApplication::applicationDirPath ();
	strMplayer += "/mplayer.exe";
	QFile file(strMplayer);
	if(!file.exists()){
		QMessageBox::critical(this,"RadioGet","程序目录下没有mplayer，无法正常工作！");
	}
#endif
	QObject::connect(&m_http,SIGNAL(done(bool)),this,SLOT(on_radiolist_done(bool)));
	m_http.setHost("radioget.googlecode.com");
	m_http.get("/svn/trunk/radiolist.xml");
	//ui->btnStop->hide();
	ui->btnStop->setEnabled(false);
	/*ui->btnStop->SetPicture(":/png/images/stop.png");
	ui->btnStop->SetMovePicture(":/png/images/stop_enter.png");
	ui->btnStop->SetDownPicture(":/png/images/stop_down.png");*/
}

MainWindow::~MainWindow()
{
	if(m_pProcess!=NULL){
		QString str="quit 0\n";
		m_pProcess->write(str.toLocal8Bit());
		m_pProcess->waitForFinished();
		m_pProcess->close();
		delete m_pProcess;
		m_pProcess=NULL;
	}
	delete ui;
}

void MainWindow::on_radiolist_done(bool error)
{
	if(error)return;

	m_baRadioData = m_http.readAll();
	//QMessageBox::critical(window(),"RadioGet",strXml);

	QDir dir(QDir::homePath () + "/.radioget");
	QString strFileName = dir.absoluteFilePath("radiolist.xml");
	//qDebug()<<strFileName;
	QFile file(strFileName);
	if(file.open(QIODevice::WriteOnly|QIODevice::Truncate))
	{
		file.write(m_baRadioData);
		file.close();
	}
	UpdateTree();
}

bool MainWindow::ReadXml()
{
	QDir dir(QDir::homePath () + "/.radioget");
	QString strFileName = dir.absoluteFilePath("radiolist.xml");
	QFile file(QFile::exists(strFileName)?strFileName:":/xml/radiolist.xml");
	if(!file.exists())return false;
	if(!file.open(QIODevice::ReadOnly|QIODevice::Text))
		return false;
	m_baRadioData = file.readAll();
	file.close();
	bool bRet=UpdateTree();
	return bRet;
}

bool MainWindow::UpdateTree()
{
	QByteArray ba = m_baRadioData;

	QString errorStr;
	int errorLine;
	int errorColumn;

	if (!m_domDocument.setContent(ba, true, &errorStr, &errorLine,&errorColumn))
	{
		QMessageBox::information(this, tr("RadioGet"),
				tr("Parse error at line %1, column %2:\n%3")
				.arg(errorLine)
				.arg(errorColumn)
				.arg(errorStr));
		return false;
	}

	QDomElement root = m_domDocument.documentElement();
	if (root.tagName() != "RadioGet") {
		QMessageBox::information(this, tr("RadioGet"),
				tr("The file is not an RadioGet radio list file."));
		return false;
	}

	m_map.clear();
	ui->treeWidget->clear();

	//处理自定义项
	QString strHome = QDir::homePath ();
	QFile file(strHome + "/.radioget/custom.conf");
	if(file.open(QIODevice::ReadOnly|QIODevice::Text))
	{
		QTreeWidgetItem *pItem = new QTreeWidgetItem( (QTreeWidget*)0, QStringList( "自定义" ) );
		while(1){
			QByteArray ba=file.readLine();
			if(ba.isEmpty())break;
			QString str(ba);
			str=str.trimmed();
			if(str.startsWith(";"))continue;
			if(str.startsWith("#"))continue;
			int npos=str.indexOf("=");
			if(npos<=0)continue;
			QString strRadioName=str.left(npos);
			QString strRadioUrl=str.mid(npos+1);
			QTreeWidgetItem *pItem1 = new QTreeWidgetItem( (QTreeWidget*)0, QStringList( strRadioName ) );
			pItem->addChild(pItem1);
			m_map.insert(strRadioName,strRadioUrl);
		}
		file.close();
		ui->treeWidget->addTopLevelItem(pItem);
	}

	//处理电台列表
	QDomNodeList radiotag=root.childNodes();
	for(uint i=0;i<radiotag.length();i++)
	{
		QDomNode node=radiotag.item(i);
		QDomElement element=node.toElement();
		if(element.attribute("hidden")=="true")continue;
		QString strRadioType=element.attribute("tag");
		//QMessageBox::information(window(),"debug",strRadioType);
		if(strRadioType=="自定义")continue;
		QTreeWidgetItem *pItem = new QTreeWidgetItem( (QTreeWidget*)0, QStringList( strRadioType ) );

		QDomNodeList radio=element.childNodes();
		for(uint j=0;j<radio.length();j++)
		{
			QDomNode node=radio.item(j);
			QDomElement element=node.toElement();
			if(element.attribute("hidden")=="true")continue;
			QString strRadioName=element.attribute("tag");
			QString strRadioUrl=element.attribute("url");
			QTreeWidgetItem *pItem1 = new QTreeWidgetItem( (QTreeWidget*)0, QStringList( strRadioName ) );
			pItem->addChild(pItem1);
			m_map.insert(strRadioName,strRadioUrl);
		}
		ui->treeWidget->addTopLevelItem(pItem);
	}
	 
	return true;
}

void MainWindow::on_mplayer_readyReadStandardOutput()
{
	if(m_pProcess==NULL)return;

	QString str=m_pProcess->readAllStandardOutput();
	if(str.indexOf("Starting playback")>=0){
		int value = ui->horizontalSlider->value();
		QString str=QString("volume %1 65535\n").arg(value);
		m_pProcess->write(str.toLocal8Bit());
	}
	else if(str.indexOf("Exiting... (End of file)")>=0){
		int n=0;
		QMap<QString,int>::iterator it = m_mapInvalidUrl.find(m_strCurrentUrl);
		if( it != m_mapInvalidUrl.end() )
			n = m_mapInvalidUrl[m_strCurrentUrl];
		n++;
		if(n<=3){
			m_mapInvalidUrl[m_strCurrentUrl] = n;
			PlayUrl(m_strCurrentUrl);
		}
	}
	//qDebug()<<"-----------"<<str<<"-----------";
	ui->textEdit->clear();
	QRegExp rx(".*%\\s+(\\d+%|\\d+\\.\\d+%)\\s*.{0,4}$");
	QRegExp rx1("^Connected\\s*$");
	QRegExp rx2(".*Cache fill:\\s+(\\d+\\.\\d+%).*");
	if(rx.indexIn(str)!=-1)
		str = QString("缓冲") + rx.cap(1);
	else if(rx1.indexIn(str)!=-1)
		str = "已连接";
	else if(rx2.indexIn(str)!=-1)
		str = QString("请稍候，正在缓冲...") + rx2.cap(1);
	else if(str.indexOf("Exiting... (End of file)")>=0)
		str = "就绪";
	ui->textEdit->append(str);
}

void MainWindow::on_mplayer_readyReadStandardError()
{
	if(m_pProcess==NULL)return;

	QString str=m_pProcess->readAllStandardError();
	ui->textEdit->clear();
	ui->textEdit->append(str);
}

void MainWindow::on_treeWidget_itemClicked(QTreeWidgetItem* item, int column)
{
	if(item->childCount()>0)return;

	QString strRadioName = item->text(column);
	m_strCurrentUrl = m_map[strRadioName];

	PlayUrl(m_strCurrentUrl);
}

void MainWindow::PlayUrl(QString& strUrl)
{
	if(m_pProcess!=NULL){
		QString str="quit 0\n";
		m_pProcess->write(str.toLocal8Bit());
		m_pProcess->waitForFinished(3000);
		m_pProcess->close();
		delete m_pProcess;
	}
	QStringList arguments;
	arguments << "-slave";
	//arguments << "-quiet";
	arguments << strUrl;
	m_pProcess = new QProcess();
	m_pProcess->setProcessChannelMode(QProcess::MergedChannels);
	QObject::connect(m_pProcess,SIGNAL(readyReadStandardOutput()),this,SLOT(on_mplayer_readyReadStandardOutput()));
	QObject::connect(m_pProcess,SIGNAL(readyReadStandardError()),this,SLOT(on_mplayer_readyReadStandardError()));
	QString strMplayer;
#ifdef Q_OS_WIN32
	strMplayer=QCoreApplication::applicationDirPath ();
	strMplayer += "/mplayer.exe";
#else
	strMplayer="/usr/bin/mplayer";
#endif
	m_pProcess->start(strMplayer, arguments);

	//ui->btnStop->show();
	ui->btnStop->setEnabled(true);
	ui->btnPause->setEnabled(true);
	ui->btnPlay->setEnabled(false);
	pauseAction->setEnabled(true);
	stopAction->setEnabled(true);
	playAction->setEnabled(false);

}

void MainWindow::on_tray_activated ( QSystemTrayIcon::ActivationReason reason )
{
	switch(reason)
	{
	case QSystemTrayIcon::Trigger:
		if (!isVisible())
		{
			showNormal();
			raise();
		}
		else
		{
			hide();
		}
		
		break;
	case QSystemTrayIcon::Context:
		break;
	case QSystemTrayIcon::DoubleClick:
		break;
	default:
		break;
	}
}


void MainWindow::on_pushButton_clicked()
{
	this->hide();
}

void MainWindow::on_action_Showaddress_triggered()
{
	QMessageBox::information(this,"当前电台地址",m_strCurrentUrl);
}
void MainWindow::on_action_triggered()
{
	QMessageBox::information(this,"RadioGet","这是一个网络收音机程序，可以收听收看到不少的广播、电视节目。\n"
			"项目主页： https://code.google.com/p/radioget");
}

void MainWindow::on_action_RadioGet_triggered()
{
	AboutWidget *paw = new AboutWidget();
	QRect tmpRect = this->geometry();
	paw->setGeometry(tmpRect);
	paw->setWindowModality(Qt::ApplicationModal);
	paw->showNormal();
}

void MainWindow::on_action_Custom_triggered()
{
	CustomDialog cd;
	cd.exec();
	UpdateTree();
}


void MainWindow::on_horizontalSlider_valueChanged(int value)
{
	if(m_pProcess==NULL)return;
	QString str=QString("volume %1 65535\n").arg(value);
	//QMessageBox::information(0,"debug",str);
	m_pProcess->write(str.toLocal8Bit());
}

void MainWindow::on_horizontalSlider_sliderMoved(int position)
{
	if(m_pProcess==NULL)return;
	QString str=QString("volume %1 65535\n").arg(position);
	//QMessageBox::information(0,"debug1",str);
	m_pProcess->write(str.toLocal8Bit());
}

void MainWindow::on_btnStop_clicked()
{
	if(m_pProcess==NULL)return;
	QString str="quit 0\n";
	m_pProcess->write(str.toLocal8Bit());
	//ui->btnStop->hide();
	//
	ui->btnStop->setEnabled(false);
	stopAction->setEnabled(false);
	ui->btnPlay->setEnabled(false);
	playAction->setEnabled(false);
	ui->btnPause->setEnabled(false);
	pauseAction->setEnabled(false);
}

void MainWindow::on_btnPause_clicked()
{
	if(m_pProcess==NULL)return;
	QString str="pause 0\n";
	m_pProcess->write(str.toLocal8Bit());

	ui->btnPause->setEnabled(false);
	pauseAction->setEnabled(false);
	ui->btnPlay->setEnabled(true);
	playAction->setEnabled(true);
}

void MainWindow::on_btnPlay_clicked()
{
	if(m_pProcess==NULL)return;
	QString str="run 0\n";
	m_pProcess->write(str.toLocal8Bit());

	ui->btnPlay->setEnabled(false);
	playAction->setEnabled(false);
	ui->btnPause->setEnabled(true);
	pauseAction->setEnabled(true);
}

void MainWindow::createActions()
{
	playAction = new QAction(("播  放"), this);
	playAction->setEnabled(false);
	connect(playAction, SIGNAL(triggered()), this, SLOT(on_btnPlay_clicked()));

	pauseAction = new QAction(("暂  停"), this);
	pauseAction->setEnabled(false);
	connect(pauseAction, SIGNAL(triggered()), this, SLOT(on_btnPause_clicked()));

	stopAction = new QAction(("停  止"), this);
	stopAction->setEnabled(false);
	connect(stopAction, SIGNAL(triggered()), this, SLOT(on_btnStop_clicked()));

	minimizeAction = new QAction(("最小化"), this);
	connect(minimizeAction, SIGNAL(triggered()), this, SLOT(hide()));

	maximizeAction = new QAction(("最大化"), this);
	connect(maximizeAction, SIGNAL(triggered()), this, SLOT(showMaximized()));

	restoreAction = new QAction(("显  示"), this);
	connect(restoreAction, SIGNAL(triggered()), this, SLOT(showNormal()));

	quitAction = new QAction(("退  出"), this);
	connect(quitAction, SIGNAL(triggered()), qApp, SLOT(quit()));
}

void MainWindow::setVisible(bool visible)
{
	minimizeAction->setEnabled(visible);
	maximizeAction->setEnabled(!isMaximized());
	restoreAction->setEnabled(isMaximized() || !visible);
	QMainWindow::setVisible(visible);
}

void MainWindow::on_btnCloseScreen_clicked()
{
#ifdef Q_OS_WIN32
	QMessageBox::warning(this,"警告","Windows不支持此功能！");
#else
	QStringList arg;
	arg<<"dpms";
	arg<<"force";
	arg<<"standby";
	QProcess *p=new QProcess;
	p->start("/usr/bin/xset",arg);
	p->waitForStarted(3000);
#endif
}
